package commonService

import (
	"fmt"
	"github.com/Sir-yuChen/funAnalyse/global"
	"github.com/Sir-yuChen/funAnalyse/model"
	"github.com/Sir-yuChen/funAnalyse/model/common/ApiReturn"
	"github.com/Sir-yuChen/funAnalyse/model/request"
	"github.com/Sir-yuChen/funAnalyse/model/resp"
	"github.com/Sir-yuChen/funAnalyse/utils"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
	"strings"
)

// GetStockTableStructure 表结构
func GetStockTableStructure(tableName string) ApiReturn.ApiReturnCode {
	apireturn := ApiReturn.OK
	dbcolumns := utils.NewDBColumns()
	dbcolumns.TableName = tableName
	columns, e := dbcolumns.GetDBColumns()
	if e != nil {
		apireturn = ApiReturn.UnknownErr
		apireturn.Msg = e.Error()
	} else {
		apireturn.Data = columns
	}
	return apireturn
}

// ExportToExcel 导出文件
func ExportToExcel(req *request.ExportExcelInfo, c *gin.Context) ApiReturn.ApiReturnCode {
	apireturn := ApiReturn.OK
	//数据索引 避免map无序导致数据导出顺序颠倒
	headers := make([]map[string]string, 0)
	//导出所有字段
	dbcolumns := utils.NewDBColumns()
	dbcolumns.TableName = req.TableName
	columns, e := dbcolumns.GetDBColumns()
	if e != nil {
		apireturn = ApiReturn.UnknownErr
		apireturn.Msg = e.Error()
		return apireturn
	}
	allHeaders := make([]map[string]string, 0)
	for _, column := range columns {
		itemMap := map[string]string{}
		itemMap["key"] = column.ColumnName
		//{"key": "title", "title": "商品", "width": "20", "is_num": "0","comment":"备注"}
		itemMap["title"] = column.ColumnName
		itemMap["comment"] = column.ColumnComment
		itemMap["width"] = "20"
		itemMap["is_num"] = "0"
		allHeaders = append(allHeaders, itemMap)
	}
	//组装headers
	if req.AllField {
		headers = allHeaders
	} else {
		//导出部分字段
		fields := strings.Split(req.Fields, ",")
		for _, field := range fields {
			for _, header := range allHeaders {
				for k, v := range header {
					if k == "key" && field == v {
						headers = append(headers, header)
					}
				}
			}
		}
	}
	sheet := utils.FirstCharUpper(req.TableName)
	//判断是否需要添加sheet 从1开始到1048576, 超过的部分则需要切到下一个Sheet
	excel := utils.NewMyExcel()
	excel.FileName = req.TableName
	//定义二维数组 初始化 赋值
	totalPage := (req.ExportNumber + 10000 - 1) / 10000
	var dataList = make([][]map[string]interface{}, totalPage)
	var index int
	for i := 0; i < totalPage; i++ {
		list := []map[string]interface{}{}
		//Sheet1 大写
		if excel.SheetName == "" {
			excel.SheetName = fmt.Sprintf("%s%d", sheet, i)
		} else {
			excel.SheetName += fmt.Sprintf("%s%s%d", ",", sheet, i)
		}
		for k := 0; k < 10000; k++ {
			m := req.ExportDatas[index]
			list = append(list, m)
			if index >= len(req.ExportDatas)-1 {
				break
			}
			index++
		}
		dataList[i] = list
	}
	excel.ExportToWeb(headers, dataList, c)
	return apireturn
}

// ReadDataFromExcel 读取表格中的数据
func ReadDataFromExcel(req model.StockFilesModel) (se resp.ReadExcelReqponse, e error) {
	excel := utils.NewReadExcel()
	excel.ExcelFile = req
	se.ExcelFile = req
	data, err := excel.ReadFromExcel()
	if err != nil {
		global.GVA_LOG.Error("读取文件数据异常", zap.Error(err), zap.Any("StockFilesModel", req))
		return se, err
	}
	se.ExcelData = data.ExcelData
	se.ReadNumber = data.ReadNumber
	return se, nil
}
